<template>
  <div>
    <div v-if="!editMode">
      <div v-html="renderedMarkdown" class="markdown-body"></div>
      <el-button @click="editMode = true" type="primary" link>编辑</el-button>
    </div>
    <div v-else>
      <el-input
        type="textarea"
        v-model="editableContent"
        :rows="20"
        placeholder="请输入Markdown内容"
      />
      <div class="mt-10px">
        <el-button @click="saveChanges" type="primary">保存</el-button>
        <el-button @click="cancelEdit">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import MarkdownIt from 'markdown-it'
import 'highlight.js/styles/github.css';

const props = defineProps<{
  content: string
}>()

const emit = defineEmits(['update:content'])

const editMode = ref(false)
const editableContent = ref('')

const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    highlight: function (str, lang) {
        const hljs = require('highlight.js');
        if (lang && hljs.getLanguage(lang)) {
            try {
                return '<pre><code class="hljs">' +
                    hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                    '</code></pre>';
            } catch (__) {}
        }

        return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
    }
});

const renderedMarkdown = computed(() => {
  return md.render(props.content || '')
})

watch(() => props.content, (newVal) => {
  editableContent.value = newVal
}, { immediate: true })

const saveChanges = () => {
  emit('update:content', editableContent.value)
  editMode.value = false
}

const cancelEdit = () => {
  editableContent.value = props.content
  editMode.value = false
}
</script>

<style scoped>
.markdown-body {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>